package com.example.leo.mycharmingstudent.a0907;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.example.leo.mycharmingstudent.R;
import com.example.leo.mycharmingstudent.a0905.ToastUtil;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class OkHttpActivity extends AppCompatActivity {

    private static final String TAG = "OkHttpActivity";

    //同步get请求按钮
    private Button btnGetSync;
    //异步get请求按钮
    private Button btnGetAsync;
    //异步post请求按钮
    private Button btnPostAsync;
    //展示的接口返回内容
    private TextView tvContent;
    private ListView mListView;
    private MyAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ok_http);

        findViews();
        initData();
        initEvent();

    }

    private void findViews() {
        btnGetSync = findViewById(R.id.btn_get_sync_activity_ok_http);
        btnGetAsync = findViewById(R.id.btn_get_async_activity_ok_http);
        btnPostAsync = findViewById(R.id.btn_post_async_activity_ok_http);
        tvContent = findViewById(R.id.tv_content_activity_ok_http);
        mListView = findViewById(R.id.lv_activity_ok_http);
    }

    private void initData() {
        /*
        向上转型 安全的、自动的
        向下转型 强转  不安全的
         */
        /*Button btnTest = (Button) btnGetSync;
        int btnIntTest = (Integer) btnGetSync;*/
    }

    private void initEvent() {
        btnGetSync.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getSync();
            }
        });
        btnGetAsync.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAsync();
            }
        });
        btnPostAsync.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                postAsync();
            }
        });
    }

    /**
     * 同步get请求方法
     */
    private void getSync() {
        tvContent.setText("");
//        1.创建Okhttp客户端       OkhttpClient
        OkHttpClient client = new OkHttpClient();
//        2.创建Request请求构建者  Request.Builder
        Request.Builder builder = new Request.Builder();
        //设置请求的url
        builder.url("https://wanandroid.com/wxarticle/chapters/json");
//        3.构建Request请求
        Request request = builder.build();
//        4.创建呼叫                Call
        final Call call = client.newCall(request);

        /*
        1.主线程中不可以进行网络操作
        2.call.execute()方法属于同步执行
        3.getSync()方法在主线程中执行的
         */
        /*try {
            //此处是在主线程中进行网络请求
            *//*
            化学反应结果：android.os.NetworkOnMainThreadException
             *//*
            Response response = call.execute();
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //5.调用方法执行
                    Response response = call.execute();
                    ResponseBody body = response.body();
                    final String result = body.string();
                    /*
                    android.view.ViewRootImpl$CalledFromWrongThreadException:
                     Only the original thread that created a view hierarchy can touch its views.
                     异常原因：子线程中更新UI
                     tvContent.setText(result);
                     */
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvContent.setText(result);
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 异步get请求
     */
    private void getAsync() {
        tvContent.setText("");

//        1.创建Okhttp客户端       OkhttpClient
        OkHttpClient client = new OkHttpClient();
//        2.创建Request请求构建者  Request.Builder
        Request.Builder builder = new Request.Builder();
        builder.url("https://wanandroid.com/wxarticle/chapters/json");
//        3.构建Request请求
        Request request = builder.build();
//        4.创建呼叫                Call
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            /**
             * 执行在子线程
             */
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, e.getMessage());
            }

            /**
             * 执行在子线程
             */
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                Gson gson = new Gson();
                final ChapterEntity chapterEntity = gson.fromJson(result, ChapterEntity.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        /*
                        匿名内部类访问局部变量的时候，
                        这个局部变量需要设置为final类型
                         */
//                        tvContent.setText(result);
                        int errorCode = chapterEntity.getErrorCode();
                        List<ChapterEntity.DataBean> data = chapterEntity.getData();
                        mAdapter = new MyAdapter(data);
                        mListView.setAdapter(mAdapter);
                        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                String format = String.format("position:%d id:%d", position, id);
                                ToastUtil.showToast(OkHttpActivity.this,format);
                            }
                        });
//                        String format = String.format("code:%d list.size:%d", errorCode, data.size());
//                        tvContent.setText(format);
                    }
                });
            }
        });
    }

    /**
     * 异步post请求
     */
    private void postAsync() {
        tvContent.setText("");
        String loginUrl = "https://www.wanandroid.com/user/login";
//        1.创建Okhttp客户端       OkhttpClient
        OkHttpClient client = new OkHttpClient();
//        由于是post请求，需要FromBody对象，接下来两步创建FromBody对象
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        FormBody formBody = formBodyBuilder.add("username", "wangxiaoer")
                .add("password", "123456")
                .build();
//        2.创建Request请求构建者  Request.Builder
        Request.Builder builder = new Request.Builder();
        builder.url(loginUrl)
                .post(formBody);
//        3.构建Request请求
        Request request = builder.build();
//        4.创建呼叫                Call
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvContent.setText(result);
                    }
                });
            }
        });
    }

    public class MyAdapter extends BaseAdapter {

        private List<ChapterEntity.DataBean> mList = new ArrayList<>();

        public MyAdapter(List<ChapterEntity.DataBean> list){
            this.mList = list;
        }

        /**
         * 获取条目数量
         */
        @Override
        public int getCount() {
            return mList.size();
        }

        /**
         * 获取当前位置的数据
         */
        @Override
        public ChapterEntity.DataBean getItem(int position) {
            return mList.get(position);
        }

        /**
         * 获取item id
         *
         * @param position
         * @return
         */
        @Override
        public long getItemId(int position) {
            return position;
        }

        /**
         * 创建视图View
         *
         * @param convertView 复用View
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            /*
            先判断convertView是不是null，
            如果是null，使用LayoutInflater创建一个View
            如果不为null，拿来直接用
             */
            //第一步，创建View
            if (convertView == null) {
                convertView = LayoutInflater
                        .from(OkHttpActivity.this)
                        .inflate(R.layout.item_activity_ok_http, null, false);
            }
            //第二步，获取控件
            TextView tvName = convertView.findViewById(R.id.tv_name_item_activity_ok_http);
            TextView tvOrder = convertView.findViewById(R.id.tv_order_item_activity_ok_http);
            //第三步，填充数据
            ChapterEntity.DataBean item = getItem(position);
            tvName.setText(String.format("name:%s", item.getName()));
            tvOrder.setText(String.format("order:%d", item.getOrder()));
            return convertView;
        }
    }
}
